package vip.meet.datasource;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;


@Component
@Aspect
public class DataSourceAspect {
    

    @Pointcut("@annotation(cn.freemethod.datasource.DataSourceKey)")
//    @Pointcut("this(cn.freemethod.service.UserService)")
    public void dataSourceKey() {}

    @Before("dataSourceKey() && @annotation(dataSourceKey)")
    public void doBefore(JoinPoint point, DataSourceKey dataSourceKey) {
//        MethodSignature signature = (MethodSignature) point.getSignature();
//        Method method = signature.getMethod();
//        DataSourceKey datasource = method.getAnnotation(DataSourceKey.class);
        if (dataSourceKey != null) {
            String sourceKey = DataSourceKey.master;
            if (dataSourceKey.value().equals(DataSourceKey.master)) {
                sourceKey = DataSourceKey.master;
            } else if (dataSourceKey.value().equals(DataSourceKey.slave)) {
                sourceKey = DataSourceKey.slave;
            }
            DataSourceKeyThreadHolder.setDataSourceKey(sourceKey);
        }
    }
    

    @After("dataSourceKey()")
    public void doAfter(JoinPoint point) {
        DataSourceKeyThreadHolder.clearDataSourceKey();
    }
}
